/**
 * 工具类， 暴露全局$F对象
 */
(function ($) {
    var dbtimeObject
        , localTime
        , localTimeSyncTimer
        , localTimeSyncInterval = 1000
        , margueeImgTimer = 0
        , _imageViewer;
    $F = {
        showAlert: function (msg) {
            var confirmAlert = $('<div class="confirm-alert"></div>').appendTo('.main').fadeIn(2000);
            confirmAlert.append('<p class="message-content">' + msg + '</p>');
            var timer = setInterval(function () {
                confirmAlert.fadeOut(1000, function () {
                    confirmAlert.remove();
                })
                clearInterval(timer);
            }, 3000);
        },
        showConfirm: function (msg, confirmFunc, cancelFunc, a, isImage) {
            var imgShow = a || false;
            var confirmContainer = $('.confirm-container');
            var confirmContainerBtn;
            if (imgShow) {
                var title = i18n.page.sendFiles;
                if (isImage) {
                    title = i18n.page.sendPictures
                }
                confirmContainerBtn = $(' <div class="confirm-title">' + title + '</div>' +
                    '<div class="msg">' + msg +
                    '</div>' +
                    '<div class="btn-container"><a class="confirm-btn">' + i18n.page.endChatConfirmBtn + '</a>' +
                    '<a class="cancel-btn">' + i18n.page.endChatCancelBtn + '</a>' +
                    '</div>');
            } else {
                confirmContainerBtn = $('<div class="msg">' + msg +
                    '</div>' +
                    '<div class="btn-container"><a class="confirm-btn">' + i18n.page.endChatConfirmBtn + '</a>' +
                    '<a class="cancel-btn">' + i18n.page.endChatCancelBtn + '</a>' +
                    '</div>');
            }
            if (confirmContainer.length > 0) {
                $('.confirm-container .msg').html(msg);
            } else {
                var hei = $("html").height();
                var wid = $("html").width();
                var mheight = (hei - 150) / 2;
                var mwidth = (wid - 300) / 2;
                confirmContainer = $('<div class="confirm-container"></div>').css({
                    "left": mwidth,
                    "top": mheight
                })
                $("body").append(confirmContainer);
            }
            confirmContainer.html(confirmContainerBtn);
            confirmContainer.show();
            $('.confirm-btn', confirmContainer).off().on('click', function () {
                $('.confirm-container').hide();
                $('.bg_cover').hide();
                //$F.appendTextToDiv("clientResponseDiv", $F.formatNotice(i18n.page.chattingOver));
                //读取配置文件是否弹出满意度
                if ($.isFunction(confirmFunc)) {
                    confirmFunc();
                }
            });

            $('.cancel-btn', confirmContainer).off().on('click', function () {
                $('.confirm-container').hide();
                $('.bg_cover').hide();
                if ($.isFunction(cancelFunc)) {
                    cancelFunc();
                }
            });
            $('.bg_cover').show();
        },
        getCancelRequestJSON: function () {
            var cancelRequestJSON = {
                actionType: "cancelRequest",
                chatRequestId: _chatRequestId
            };
            return JSON.stringify(cancelRequestJSON);
        },
        giveUpChat: function () {
            $F.showConfirm($config.confirmRequestCancelMessage, function () {
                $F.log("点击了取消排队:确定");
                if (_chatRequestId != -1) {
                    $F.doAjaxCall(Constants.ajaxURL, "requestType=send&data=" + $F.getCancelRequestJSON(), function (sendResponse) {
                        //如果包含有机器人而且是转人工的情况下就不需要设置成false
                        if (sendResponse.result == 1) {
                            _chatRequestId = -1;
                            if (!$ROBOT.hasRobot()) {
                                _sessionActive = false;
                                $config.sessionId = -1;
                                if (_pullTimer) {
                                    clearTimeout(_pullTimer);
                                }
                                $("#minBarDiv").parent().remove();
                                $("#leaveMsg_div").click(); //如果直接跟人聊天的时候取消排队的时候就要直接跳转留言界面
                            } else {
                                UI.robot();
                            }
                            $F.formatAndShowNotice($config.requestCancelledMessage, false);
                        } else {
                            if (sendResponse.feedbackMessage)
                                $F.formatAndShowNotice(response.feedbackMessage, false);
                        }
                    });
                }
            }, function () {
                $F.log("点击了取消排队:取消");
                if ($ROBOT.hasRobot()) {
                    UI.robotOnlYChangeUI();
                }
            })
        },
        showATag: function (url, name) {
            window.open(url, name, "height=560,width=980,top=80,left=100,resizable=0,location=no,status=no,titlebar=no,toolbar=no,menubar=no,scrollbars=no");

        },
        openATag: function (type, url, name, classA, styleA) {
            if (!type) type = 0;
            if (type == 0) {
                return '<a class="' + classA + '" href="' + url + '"  class="' + styleA + '" target="_blank">' + name + '</a>';
            } else if (type == 1) {
                result = '<a class="' + classA + '" href="###"  class="' + styleA + '" onclick="$F.showATag(\'' + url + '\', \'' + name + '\');">' + name + '</a>';
                return result;
            } else {
                return null;
            }
        },
        getSessionRatingJSON: function (ratingId, comments, extendInfo, type) {
            return JSON.stringify({
                clientId: Constants.client.clientId,
                chatSessionId: $config.thisSessionId,
                ratingId: ratingId,
                ratingComment: comments.replaceAll('\r\n', '<br>').replaceAll('\n\r', '<br>').replaceAll('\r', '<br>').replaceAll('\n', '<br>'),
                ratingExtendVOList: extendInfo
            });
        },
        getRatings: function () {
            var ratingValue = [];
            if (!Constants.agent.id) {
                ratingValue = (typeof robotRatings !== 'undefined' && robotRatings && robotRatings.length > 0) ? robotRatings : ratings
            } else {
                ratingValue = ratings
            }
            return ratingValue
        },
        getRatingExtendInfoJSON: function (ratingId, ratingExtendId, ratingExtendType, ratingExtendValue) {
            return {
                chatSessionId: $config.thisSessionId,
                ratingId: ratingId,
                ratingExtendId: ratingExtendId,
                ratingExtendType: ratingExtendType,
                ratingExtendValue: ratingExtendValue
            };
        },

        hrefEndUrl: function () {
            if ($config.queue.endUrl) {
                if (!_sessionActive) {
                    window.location = $config.queue.endUrl;
                }
            } else {
                if (config && config.page && config.page.endTurnPage && !Constants.OpenRate.hasRating) {
                    if ($config.queue.endUrl || config.page || config.page.endUrl) {
                        setTimeout(function () {
                            window.location = $config.queue.endUrl || config.page.endUrl;
                        }, 2000);
                    }
                } else {
                    if (!(window.self === window.top)) { //当前被嵌入到了iframe中
                        window.parent.close();
                    }
                }
            }
        },

        rateAfter: function (str) {
            clearShowRatingTimer();
            if (Constants.rate.rateSender == Constants.rate.rateType.CLIENT_CLOSE) {
                if (Constants.rate.client.rateOrEnd == Constants.rate.openRate.AFTER_CLOSE) {
                    if (_sessionActive) {
                        var closeSessionJSON = {
                            actionType: "closeSession",
                            senderId: Constants.client.clientId,
                            senderName: Constants.client.clientName,
                            sessionId: $config.sessionId,
                            closeType: Constants.CloseType.CLIENT_CLOSE
                        };
                        $F.doAjaxCall(Constants.ajaxURL, {
                            requestType: 'send',
                            data: JSON.stringify(closeSessionJSON)
                        });
                        $config.chatTime = 0;
                        $("#time").html(i18n.page.sessionEndNoActive);
                        _sessionActive = false;
                        $config.sessionId = -1;
                        UI.doEnd();
                    }
                }
                $F.hrefEndUrl();
            }
            if (typeof (aterRatePage) != 'undefined' && $.isFunction(aterRatePage))
                aterRatePage();
        },
        /**
         * 判断一个文件名后缀是不是属于图片类型
         * @param fileName
         */
        isImage: function (fileName) {
            if (fileName.lastIndexOf('.') > -1) {
                fileName = fileName.substring(fileName.lastIndexOf('.') + 1);
            }
            var exts = ['PNG', 'JPG', 'JPEG', 'BMP', 'GIF'];
            for (var i = 0; i < exts.length; i++) {
                var ext = exts[i];
                if (this.equalsIgnoreCase(fileName, ext)) {
                    return true;
                }
            }
            return false;
        },
        /**
         * 忽略大小写进行比较
         * @param s {string} 比较源
         * @param t {string} 比较目标
         * @return {boolean}
         */
        equalsIgnoreCase: function (s, t) {
            if (this.isEmpty(s) && this.isEmpty(t)) {
                return true;
            }
            if (!this.isEmpty(s) && !this.isEmpty(t) && s.toLowerCase() == t.toLowerCase()) {
                return true;
            }
            return false;
        },
        /**
         * 判断某个对象是否为undefined或者null或者空字符串
         * @method isEmpty
         * @param {string} object 对象
         * @return {boolean}
         */
        isEmpty: function (e) {
            return (e == undefined || e == null || (typeof (e) == "string" && $.trim(e) == ""));
        },
        /**
         * 过滤字符中url，用a标签包装识别出来的url。只会包装dom元素的text内容，而不会去包装dom的属性中的url
         */
        wrapURL: function (str) {
            try {
                if ($(str).length > 0) {
                    return str;
                }
            } catch (e) {
            }
            var matchURLs = $('<div>').append(str).text().match(/(((https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www\..|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)(?::(\d+))?((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\+~%\/.\w-_\?=&;%@]*))?)((?!http|([u4e00-u9fa5])*).)*/g);
            if (matchURLs) {
                matchURLs = matchURLs.filter(function (item, index, self) {
                    return self.indexOf(item) === index;
                });
                $.each(matchURLs, function (i, url) {
                    //经过text()方法后，字符串中的&amp;会变成& 这里要判断一下，如果存在这种情况，就要再replace一次
                    var parsedUrl = url.replace(/&/g, '&amp;').replace(/\?/g, '\\?');
                    str = str.replace(new RegExp(parsedUrl, 'g'), function (matchStr) {
                        var url = matchStr;
                        if (!matchStr.startsWith('http://') && !matchStr.startsWith('https://')) {
                            url = 'http://' + matchStr;
                        }
                        return '<a target="_blank" href="' + url + '">' + matchStr + '</a>';
                    });
                });
            }
            return str;
        },
        showOriginImage: function (img, contextPath) {
            var src = $(img).attr('data-url');
            if (!src) {
                src = img.src;
            }
            if (!contextPath)
                contextPath = '';
            if (_imageViewer) {
                _imageViewer.destroy();
            }
            $("#imageShow img").attr("src", img.src);
            _imageViewer = new Viewer($('#imageShow img')[0], {
                inline: false,
                button: true,
                title: false,
                toolbar: false,
                tooltip: true,
                movable: true,
                loop: false,
                navbar: false,
            });
            _imageViewer.show();
        },
        parseMessageFromContainer: function (container, messageContainer, chatServerHost) {
            var self = this;
            if (!messageContainer)
                messageContainer = container;
            if (!chatServerHost) {
                chatServerHost = '';
            }
            var currentVoiceAudio;
            container.find("img:not(.avatar, .qqemoji, .standard-emoji, .location, .thumb, .emot, .tb-img, .ke-emoji, .custom-emoji, .robot-img, .ql-image)").each(function (i, img) {
                $(img).css("cursor", "pointer").off('load').on('load', function () {
                    $COMM.autoResizeImage(300, 300, this);
                    scrollToBottom();
                }).on('error', function () {
                    $(this).attr('src', 'images/error.png').attr('title', '');
                });
            });
            container.find("img:not(.avatar, .qqemoji, .standard-emoji, .location, .thumb, .emot, .tb-img, .ke-emoji, .custom-emoji)").each(function (i, img) {
                $(img).on("click", function () {
                    if (this.src.startWith('data:image')) {
                        //图片是base64的不做处理
                    } else {
                        self.showOriginImage(this);
                    }
                });
            });
            container.find("video").each(function (i, video) {
                var videoObj = $(video), src = videoObj.attr('src');
                if (!src.toLowerCase().startsWith('http')) {
                    src = chatServerHost + src;
                }
                videoObj.css("width", "300px").on("canplay", function () {
                    scrollToBottom();
                });
            });
            container.find('div.message-voice').each(function (i, voice) {
                var $voice = $(voice);
                $voice.on('click', function () {
                    var url = $voice.attr('data-url');
                    if (url) {
                        $('div.message-voice').removeClass("active");
                        if (currentVoiceAudio && !currentVoiceAudio.paused && !currentVoiceAudio.ended && 0 < currentVoiceAudio.currentTime) {
                            currentVoiceAudio.pause();
                            currentVoiceAudio.currentTime = 0;
                            $voice.removeClass('active');
                            return;
                        }
                        if (!$voice.hasClass('listened')) {
                            $voice.addClass('listened');
                        }
                        currentVoiceAudio = new Audio(url);
                        $(currentVoiceAudio).on('play', function () {
                            $voice.addClass('active');
                        }).on('ended', function () {
                            $voice.removeClass('active');
                        }).on('error', function () {
                            $voice.removeClass('active');
                        });
                        currentVoiceAudio.play();
                    }
                });
            });
            container.find('div.message-file').each(function (i, file) {
                var $file = $(file);
                $file.on('click', function () {
                    var url = $file.attr('data-url');
                    if (url) {
                        window.open(url, 'FILE_DOWNLOAD');
                    }
                });
            });
            container.find('div.message-location').each(function (i, location) {
                var $location = $(location);
                $location.on('click', function () {
                    var latitude = $location.attr('data-latitude'),
                        longitude = $location.attr('data-longitude'),
                        label = $location.attr('data-address');
                    map = $location.attr('data-map'),
                        mapUrl = 'aMaps.html';
                    if (map == 'baidu') {
                        mapUrl = 'baiduMaps.html'
                    } else if (map == 'tencent') {
                        mapUrl = 'tencentMaps.html'
                    }
                    window.open(mapUrl + '?latitude=' + latitude + '&longitude=' + longitude + '&label=' + encodeURIComponent(label), '_blank', "noopener=yes,noreferrer=yes");
                });
            });
        },
        /**
         * 返回扩展信息内容
         * @returns {*}
         */
        appendTextToDiv: function (divId, data) {
            var target;
            try {
                target = $(data);
            } catch (e) {
            }
            if (!target || target.length == 0) {
                target = $('<div>' + data + '</div>');
            }
            $F.parseMessageFromContainer(target, $("#" + divId));
            $("#" + divId).append(target);
            $F.messageFromContainer();
            scrollToBottom();
        },

        prependTextToDiv: function (divId, data) {
            var startHeight = $('#clientResponseDiv').height();
            var target;
            try {
                target = $(data);
            } catch (e) {
            }
            if (!target || target.length == 0) {
                target = $('<div>' + data + '</div>');
            }
            $F.parseMessageFromContainer(target, $("#" + divId));
            $("#" + divId).prepend(target);
            scrollToNum($('#clientResponseDiv').height() - startHeight + 20 + $(".button-load-talk").height());
            $F.messageFromContainer();
        },
        messageFromContainer: function () {
            $('.lele .avatar').on('error', function () {
                $(this).prop('src', 'jsp/standard/theme/' + $config.theme + '/img/agent.jpg?v=' + $config.version);
            });
            $('.me .avatar').on('error', function () {
                $(this).prop('src', 'jsp/standard/theme/' + $config.theme + '/img/client.jpg?v=' + $config.version);
            });
        },
        formatAndShowNotice: function (msg, top, type) {
            if (msg) {
                var domInqueueNotice = $('.inqueue-notice').parent();
                var domTransferMessageTips = $('.transfer-message-tips').parent();
                if (domInqueueNotice[0]) {
                    domInqueueNotice.remove();
                    domInqueueNotice.prepend("br").remove();
                }
                if (domTransferMessageTips[0]) {
                    domTransferMessageTips.remove();
                }
                var tips = '';
                if (type == Constants.formatNoticeType.QUEUE) { // 队列排队消息 添加queue class
                    tips = msg;
                } else if (type == Constants.formatNoticeType.OUTTIME) { // 队列排队消息 添加queue class
                    var domInqueueLoad = $('.inqueue-load').parent();
                    if (domInqueueLoad[0]) {
                        domInqueueLoad.remove();
                    }
                    var domOuttimeNotice = $('.outtime-notice');
                    if (domOuttimeNotice[0]) {
                        domOuttimeNotice.remove();
                    }
                    tips = "<div class=\"no-bg no-yel outtime-notice\"><div class=\"notice\">" + msg + "</div></div>";
                } else {
                    $('.inqueue-load').parent().remove();
                    tips = "<div class=\"no-bg no-yel\"><div class=\"notice\">" + msg + "</div></div>";
                }

                if (type == Constants.formatNoticeType.QUEUE) {
                    $F.formatNotice(tips);
                } else {
                    if (top) {
                        $F.log("显示再提示栏上" + tips);
                        $("#notice-bar").html(tips);
                        $(window).resize();
                    } else {
                        $F.log("显示在消息框里面" + tips);
                        $F.formatNotice(tips);
                    }
                }
            }
        },
        formatNotice: function (msg, pre) {
            if (pre) {
                $F.prependTextToDiv("clientResponseDiv", msg);
            } else {
                $F.appendTextToDiv("clientResponseDiv", msg);
            }

        },
        /**
         * 返回浏览器类型
         * @returns {*}
         */
        getBrowserType: function () {
            return currentBrowserType;
        },
        formatFeedbackMessage: function (msg) {
            return "<div class='no-bg no-green'><font color='#808080'>" + msg + "</font></div>";
        },
        parseDate: function (t) {
            // 日期格式化
            if (t == '')
                return new Date();

            if ($.type(t) == 'date')
                return t;

            if ($.type(t) == 'number')
                return new Date(t);

            if ($.type(t) !== 'string') {
                return new Date();
            }

            var st = t.split(' '), format;
            if (st.length < 2) {
                var subt = st[0].split(':');
                if (subt.length > 1) {
                    // 字符串为时间
                    if (subt.length == 2)
                        format = "H:i";
                    else
                        format = "H:i:s";
                } else {
                    // 字符串为日期
                    var x = subt[0].split('-').length;
                    if (x > 2)
                        format = "Y-m-d";
                    else if (x > 1)
                        format = 'Y-m';
                    else
                        format = 'Y';
                }
            } else {
                // 字符串为完整日期时间
                var subt = t.trim().split(':');
                if (subt.length > 1) {
                    // 字符串为时间
                    if (subt.length == 2)
                        format = "Y-m-d H:i";
                    else {
                        if (t.match(/^(\d{4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{2}):(\d{2}).(\d{1,3})$/))
                            format = Date.patterns.ISO8601LongestPattern;
                        else
                            format = Date.patterns.ISO8601LongPattern;
                    }
                } else {
                    // 字符串为日期
                    format = "Y-m-d H";
                }
            }
            // console.info(format);
            return Date.parseDate(t, format);
        },
        /**
         * 获取服务端当前时间 yyyy-MM-dd HH:mm:ss
         * @method getDbTime
         * @return {string}
         */
        getLocalTime: function (nS) {
            if (nS) {
                return new Date(nS).format('yyyy-MM-dd hh:mm:ss')
            }
            this.localTimeSync(); // 先sync一次，避免时间往前改造成setInterval本身不执行了
            if (dbtimeObject) {
                return new Date(Date.now() - dbtimeObject.timestamp + dbtimeObject.serverTime).format('yyyy-MM-dd hh:mm:ss');
            } else {
                clearInterval(localTimeSyncTimer);
                var result = '';
                $.ajax({
                    url: 'client/jsonHttpRemote.do',
                    method: 'POST',
                    async: false,
                    data: {
                        requestType: 'getDbTimes',
                        v: Date.now(),
                    },
                    cache: false,
                    timeout: 3000,
                    success: function (data) {
                        result = data;
                    }
                })
                if (result && result.code == 200) {
                    var nowString = result.data;
                    dbtimeObject = {
                        serverTime: $F.parseDate(nowString).getTime(),
                        timestamp: Date.now()
                    };
                    // 启动定时检查机制，避免本地时间被修改后，获取的时间都是错误的时间
                    localTimeSyncTimer = setInterval(function () {
                        $F.localTimeSync();
                    }, localTimeSyncInterval);
                    return nowString;
                }
                $F.log("$F - getDbTime", "获取数据库时间失败, ");
                var now = new Date();
                dbtimeObject = {
                    serverTime: now.getTime(),
                    timestamp: now.getTime()
                };
                return now.format('yyyy-MM-dd hh:mm:ss');
            }
        },

        localTimeSync: function () {
            if (!localTime) {
                localTime = new Date();
            }
            var now = new Date(),
                elapse = now.getTime() - localTime.getTime();
            if (elapse < 0 || elapse > 5 * localTimeSyncInterval) {
                dbtimeObject = null; // 清空数据库时间缓存，下次获取数据库时间需要重新获取
            }
            localTime = now;
        },
        /**
         * <dl class="message"><p class="system-message"><pre>发士大夫</pre></p></dl> 系统消息dom
         * @param userId
         * @param name
         * @param msg
         * @param posttime
         * @param icon
         * @returns {*}
         */
        getDisplayMessage: function (userId, name, msg, posttime, icon, messageId) {
            icon = $COMM.getUserIcon(userId, icon, {
                "clientIcon": Constants.client.iconUrl,
                "robotIcon": Constants.robot.iconUrl,
                "agentIcon": Constants.agent.iconUrls[userId] || Constants.agent.iconUrl,
                "queueId": $config.queueId
            });
            var result = "", msgId = -1, msgText = msg, messageType = 0;
            if (typeof msg === 'object') {
                msgId = msg.id;
                msgText = msg.text;
                messageType = msg.messageType;
            }

            if (userId == "-1") {
                result = '<div class="message"><p class="system-message"><pre>' + msgText + '</pre></p></div>';
            } else {
                var time = $F.getLocalTime(posttime);
                msgText = $EMOTION.filterEmojis(msgText);//解析表情
                if (userId == $config.client.clientId) {
                    var clientName = Constants.client.clientFirstName;
                    if ($config.client.clientType == 1) {
                        clientName = clientName || i18n.page.visitClientName || '';
                    }
                    result = '<div class="message clearfix me">' +
                        '<div class="nowtime me-time"><span class="me-name">' + clientName + '</span>' +
                        '<span>' + time + '</span>' +
                        '</div>' +
                        '<div><img class="avatar" src="' + icon + '" alt="' + Constants.client.iconAlt + '" /><i class="icon"></i></div>' +
                        '<pre class="content">' + msgText + '</pre>' + '<div id="' + (messageId || '') + '" class="send-result hide">!</div>' +
                        '</div>';
                } else {
                    if ($config.smbt && (messageType != 0 && messageType != 1)) {
                        result = '<div class="message"><p class="system-message">' + msgText + '</p></div>';
                    } else {
                        config.common.clientTimeInit = 0;
                        var agentName = name || Constants.agent.name || i18n.page.agentName;
                        var iconAlt = Constants.agent.iconAlt;
                        var extendDom = '';
                        if ($ROBOT.isRobot(userId)) {
                            agentName = Constants.robot.robotName || name || Constants.robot.name || i18n.robot.name;
                            iconAlt = Constants.robot.iconAlt;
                        } else if ($config.allowTTS) {
                            var ttsText = this.replaceDom(msgText);
                            var dom = $('<div>').append(msgText);
                            if (!!dom.text() && !$('a', dom).hasClass('attachment')) {
                                extendDom = '<div class="message-voice content-extend" data-url=\'/webchat/tts/generate.do?text=' + ttsText + '\'></div>'
                            }
                        }

                        result = '<div class="message clearfix lele ' + Constants.robot.robotType + '" data-id="' + msgId + '">'
                            + '<div class="nowtime lele-time">'
                            + '<span class="me-name">' + agentName + '</span><span>' + time + '</span>'
                            + '</div>'
                            + '<div><img  class="avatar" src="' + icon + '" alt="' + iconAlt + '" /><i class="icon"></i></div>'
                            + '<pre class="content">' + msgText + '</pre>' + extendDom +
                            '</div>';
                        Constants.robot.robotName = '', Constants.robot.robotType = '';
                    }
                }
            }
            return result;
        },
        /**
         * 跑马灯信息提示
         */
        loadingMarquee: function (data) {
            if (data) {
                var marquee = '';
                $.each(data, function (i, item) {
                    marquee += '<li><a href="' + item.url + '" target="_blank"> 	' + item.name + '</a> ' + item.time + '</li> ';
                })
                $("#marquee").append(marquee);
                $("#marquee").marquee({
                    yScroll: "top"        // 初始滚动方向 (还可以是"top" 或 "bottom")
                    , showSpeed: 850        // 初始下拉速度
                    , scrollSpeed: 12       // 滚动速度
                    , pauseSpeed: 5000      // 滚动完到下一条的间隔时间
                    , pauseOnHover: true    // 鼠标滑向文字时是否停止滚动
                    , loop: -1              // 设置循环滚动次数 （-1为无限循环）
                    , fxEasingShow: "swing"  // 缓冲效果
                    , fxEasingScroll: "linear"  // 缓冲效果
                    , cssShowing: "marquee-showing"  //定义class

                    // event handlers
                    , init: null               // 初始调用函数
                    , beforeshow: null           // 滚动前回调函数
                    , show: null                 // 当新的滚动内容显示时回调函数
                    , aftershow: null
                })
            }
        },

        /**
         * 轮播图片显示
         */
        loadingMargueeImg: function (margueeImgObj) {
            if (margueeImgObj) {
                var margueeImg = '';
                var carousel = '';
                $.each(margueeImgObj, function (i, item) {
                    margueeImg += ' <li class="ad">';
                    if (item.url)
                        margueeImg += '<a href="' + item.url + '"  target="_blank">';
                    margueeImg += '<img src="' + item.imgUrl + '">';
                    if (item.url)
                        margueeImg += '</a>';
                    margueeImg += '</li>';
                    if (i == 0) {
                        carousel += '<li style="background:#fff"></li>';
                    } else {
                        carousel += '<li></li>';
                    }
                });
                $(".adbox").append(margueeImg);
                $(".btnbox").append(carousel);
                $(".adbox").width(100 * parseInt(margueeImgObj.length) + '%');
                $(".btnbox").width(24 * parseInt(margueeImgObj.length));
                $(".ad").width(100 / parseInt(margueeImgObj.length) + '%');
                setTimeout(function () {
                    $F.initMargueeImg();
                }, 500)
            }
        },
        initMargueeImg: function () {
            $F.log("initMargueeImg");
            var win = $(".carousel");
            win.show();
            var width = win.width();
            var num = 0;
            if (margueeImgTimer) clearInterval(margueeImgTimer);
            margueeImgTimer = setInterval(move, 5000);

            function move() {
                num++;
                if (num == $(".btnbox li").length) {
                    num = 0;
                }
                $(".btnbox li").css("background", "#ccc").eq(num).css("background", "#fff");
                $(".adbox").animate({marginLeft: -width * num});
            }

            win.hover(function () {
                clearInterval(margueeImgTimer)
                $(".lt").css("display", "block");
                $(".rt").css("display", "block");
            }, function () {
                if (margueeImgTimer) clearInterval(margueeImgTimer);
                margueeImgTimer = setInterval(move, 3000)
                $(".lt, .rt").css("display", "none");
                $(".rt").css("display", "none");
            })
            $(".btnbox li").hover(function () {
                $(".adbox").finish();
                var index = $(".btnbox li").index(this)
                num = index;
                $(".btnbox li").css("background", "#ccc").eq(num).css("background", "#fff");
                $(".adbox").animate({marginLeft: -width * num});
            })
            $(".lt").click(function () {
                $(".adbox").finish();
                num -= 2;
                if (num < -1) {
                    num = 3
                }
                move();
            })

            $(".rt").click(function () {
                $(".adbox").finish();
                move();
            })
        },
        getPostMessageSentInfoJSON: function (msg, actionType) {
            return this.getPostMessageSentInfoJSONWithSearchKey(msg, new Date($F.getLocalTime()).getTime(), '', actionType)
        },
        /**
         *
         * @param msg
         * @param searchKey 获取发送消息内容 包含关键字搜索内容
         * @param actionType
         * @returns {string}
         */
        getPostMessageSentInfoJSONWithSearchKey: function (msg, postTime, searchKey, actionType, fromType) {
            var sentInfo = {
                senderId: $config.client.clientId,
                actionType: actionType || "postMessage",
                sessionId: $config.sessionId,
                searchKey: searchKey,
                extra: fromType || '',
                message: msg,
                postTime: postTime || new Date().getTime()
            };
            return JSON.stringify(sentInfo);
        },
        /**
         * 加载队列数据
         */
        loadingQuee: function (queueObj, callback) {
            if (queueObj) {
                var queueArr = new Array();
                var arr = queueObj.arr;
                if (arr) {
                    var queueHtml = '<div class="queue" ><em>' + i18n.common.queueWelcome + '</em><br><lu>';
                    for (var i = 0; i < arr.length; i++) {
                        queueHtml += '<li queue="' + arr[i].queueId + '"><em>' + arr[i].name + '</em></li>';
                        queueArr.push(arr[i].queueId);
                    }
                    queueHtml += '</lu></div>';
                    $F.appendTextToDiv("clientResponseDiv", $F.getDisplayMessageRobot(queueHtml));
                    callback();
                    return queueArr;
                }

            }

        },
        /**
         * 加载头部的链接
         */
        loadingHeadLink: function (headLinkObj) {
            if (headLinkObj && headLinkObj.length > 0) {
                var htmlHeadLink = '<ul class="item-list">';
                for (var i = 0; i < headLinkObj.length; i++) {
                    var obj = headLinkObj[i];
                    htmlHeadLink += '<li><a href="' + obj.hrefLink + '" target="_blank"><img src="' + obj.imgLink + '" alt="' + obj.title + '"/>';
                    if (obj.title)
                        htmlHeadLink += '<span>' + obj.title + '</span>';
                    htmlHeadLink += '</a></li>';
                }
                htmlHeadLink += '</ul>';
                $('#navBox').html(htmlHeadLink);
                $('#navBox').show();
                $(".tool-link").html(htmlHeadLink);
            }
        },

        loadingQuestLink: function () {
            var isShow = false;
            this.doAjaxCall(Constants.ajaxURL, {
                requestType: 'getCommonQuestions',
                queue: $config.queueId,
                from: _from
            }, function (data) {
                if (data) {
                    if (typeof data === 'string') {
                        $F.appendTextToDiv("clientResponseDiv", data);
                    } else {
                        if (data && data.length > 0) {
                            var htmlQuesLink = '';
                            $.each(data, function (i, item) {
                                if (parseInt(item.FLAG) == 1) {
                                    if (!isShow) {
                                        htmlQuesLink += '<div><div class="clearfix"><dd><div class="questions" data-log="true"><p>' + (i18n.common.FAQTitle) + '</p><ul>';
                                        isShow = true;
                                    }
                                    if (item.REW_URL) {
                                        htmlQuesLink += '<li><a data-id="' + item["CQ_QUID"] + '" href="' + item.REW_URL + '" target="_blank">' + item.TITLE + '</a></li>'
                                    } else {
                                        htmlQuesLink += '<li><a data-id="' + item["CQ_QUID"] + '" href="###" data=\'' + item.QUESTIONS_DESC + '\'>' + item.TITLE + '</a></li>'
                                    }
                                }
                            })
                            htmlQuesLink += '</ul></div></dd></div></div>';
                            $F.appendTextToDiv("clientResponseDiv", htmlQuesLink);

                            $(".questions a").click(function () {
                                var text = $(this).attr("data");
                                text = $F.wrapURL(text);
                                if ($config.queue.commonQuestionShowType == 0) {
                                    var time = $F.getLocalTime();
                                    $F.appendTextToDiv("clientResponseDiv", $F.getDisplayMessage(Constants.agent.id || Constants.robot.robotId, Constants.agent.name, text, ""));
                                } else {
                                    chatEditor.html(text);
                                    $("#sendBtn_div").click();
                                }

                                var dataId = $(this).data("id");
                                if (dataId) {
                                    $F.doAjaxCall(Constants.ajaxURL, "requestType=addCommonQuestionsLog&data=" + JSON.stringify({
                                        queue: $config.queue.id,
                                        from: _from,
                                        sessionId: $config.sessionId,
                                        requestId: _chatRequestId,
                                        clientId: $config.client.clientId,
                                        chatQuestionId: dataId,
                                        createdDate: new Date().getTime()
                                    }));
                                }
                            })
                        }
                    }
                }
            })
        },

        formatTopNotice: function (msg) {
            return "<div class=\"no-bg no-green\"><div class=\"notice\">" + msg + "</div></div>";
        },
        /**
         * 调用ajax请求
         * @param url
         * @param data
         * @param [successFunc]
         * @param [failFunc]
         * @param [timeout] 超时（秒）
         * @param [headers] 请求头
         */
        doAjaxCall: function (url, data, successFunc, failFunc, timeout, headers) {
            timeout = timeout || 30000;
            headers = headers || {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
            }
            return $.ajax({
                url: url,
                data: data,
                method: 'POST',
                cache: false,
                headers: headers,
                timeout: timeout,
                error: function (jqXHR, textStatus, errorThrow) {
                    $F.log("Ajax error: " + errorThrow + "  xhr status:" + jqXHR.status + " responseText: " + jqXHR.responseText);
                    if ($.isFunction(failFunc)) {
                        failFunc(jqXHR, textStatus, errorThrow);
                    }
                },
                success: function (response) {
                    var code = response.code;
                    console.log("ajax result : %o", response)
                    if (code) {
                        if (code === 401) {
                            clearTimeout(_showRatingTimer);
                            clearTimeout(_titleBlinkTimer);
                            clearTimeout(_pullTimer);
                            if (!isShowFailTips) {
                                isShowFailTips = true;
                                alert(i18n.common.afkAlert);
                            }
                            UI.doEnd();
                            if (config && config.page) {
                                location.href = endUrl;
                            }
                            if ($.isFunction(failFunc)) {
                                failFunc(response);
                            }
                        } else if (code === 200) {
                            if ($.isFunction(successFunc)) {
                                successFunc(response.data);
                            }
                        }
                    } else {
                        if ($.isFunction(successFunc)) {
                            successFunc(response);
                        }
                    }

                }
            });
        },

        /**
         * 写日志
         * @param content
         * @param server
         */
        log: function (content, server) {
            if (server) {
                $F.doAjaxCall(Constants.ajaxURL, {
                    requestType: 'writeLog',
                    content: content
                });
            }
            console.log(content);
        },

        convertEnterToBr: function (msg) {
            if (!msg)
                return msg;
            msg = msg.replace(/\r\n/ig, "<br/>");
            return msg;
        },

        replaceDom: function (str) {
            if (str) {
                var regex = /(<([^>]+)>)/ig;
                return str.replace(regex, "").replaceAll('"', '').replaceAll("'", '').replace(/[\r\n]/g, "");
            }
            return '';
        },

        encodeStringForHtmlEditor: function (str) {
            if (str == null || str == undefined)
                return str;
            else {
                str = str.replace(/\r\n/g, '').replace(/\n\r/g, '').replace(/\r/g, '').replace(/\n/g, '').replace(/\t/g, '').replace(/\b/g, '');
                str = str.replace(/\\/g, '\\\\');
                return str;
            }
        },
        encodeStringByHTMLEscape: function (str) {
            if (str == null || str == undefined)
                return str;
            else {
                //handle encoding key html characters
                str = str.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/>/g, '&gt;').replace(/</g, '&lt;');//.replace(/ /g, '&nbsp;');
                str = str.replace(/\\/g, '&#92').replace(/\//g, '&#47');
                str = str.replace(/\r\n/g, '<br/>').replace(/\n\r/g, '<br/>').replace(/\r/g, '<br/>').replace(/\n/g, '<br/>').replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;').replace(/\b/g, '');
                return str;
            }
        },

        /**
         * 去掉字符两端的空白字符
         *
         * @returns string
         */
        trimString: function (sInString) {
            sInString = sInString.replace(/^\s+/g, "");// strip leading
            return sInString.replace(/\s+$/g, "");// strip trailing
        },
        ajaxLoading: function () {
            $("<div class=\"datagrid-mask\"></div>").css({
                display: "block",
                width: "100%",
                height: $(window).height(),
                position: "absolute",
                top: 0,
                left: 0
            }).appendTo("body");
            $("<div class=\"datagrid-mask-msg\"></div>").html(i18n.page.loading).appendTo("body").css({
                display: "block",
                left: ($(document.body).outerWidth(true) - 190) / 2,
                top: ($(window).height() - 45) / 2,
                position: "absolute"
            });
            $(".clearfix").hide();
        },
        ajaxLoadEnd: function () {
            $(".datagrid-mask").remove();
            $(".datagrid-mask-msg").remove();
            $(".clearfix").show();
            $(".c-main-con").scrollTop($("#clientResponseDiv").height());
        }
    };

    function scrollToBottom() {
        $("#talkBox")[0].scrollTop = $("#talkBox")[0].scrollHeight + 30;
    }

    function scrollToNum(num) {
        $("#talkBox").scrollTop(num);
    }


    if (!window.console) {
        window.console = {
            log: function () {
            }
        }
    }

    /**
     * Fix for IE9 : Object doesn't support property or method 'createContextualFragment'
     */
    if ((typeof Range !== "undefined") && !Range.prototype.createContextualFragment) {
        Range.prototype.createContextualFragment = function (html) {
            var frag = document.createDocumentFragment(),
                div = document.createElement("div");
            frag.appendChild(div);
            div.outerHTML = html;
            return frag;
        }
    }

    if (document.all) {
        $("a[href='javascript:;']").on("click", function (e) {
            e.preventDefault();
        });
    }
})(jQuery);
